<?php

namespace Icsoc\RulesBundle\Controller;

use Doctrine\ORM\NoResultException;
use Icsoc\CoreBundle\Controller\BaseController;
use Icsoc\SecurityBundle\Entity\WinRules;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Icsoc\CoreBundle\Logger\ActionLogger;

/**
 * 日程规则管理
 * Class RulesController
 * @package Icsoc\RulesBundle\Controller
 */
class RulesController extends BaseController
{
    /**
     * 星期
     * @var array
     */
    private $week = array(0=>"周日", 1=>"周一", 2=>"周二", 3=>"周三", 4=>"周四", 5=>"周五", 6=>"周六");

    /**
     * ivr 列表
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction()
    {
        return $this->render('IcsocRulesBundle:Rules:index.html.twig');
    }

    /**
     * ivr 列表数据
     * @param Request $request
     * @return Response
     */
    public function listAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'ruleId');
        $fliter = $request->get('fliter', '');
        $where = ' AND intro.vccId = :vcc_id ';
        $parameter['vcc_id']  = $this->getUser()->getVccId();
        if (!empty($fliter)) {
            $json = json_decode($fliter, true);
            if (isset($json['keyword']) && !empty($json['keyword'])) {
                $where.="AND intro.ruleName like '%".$json['keyword']."%'";
            }
        }

        /** @var \Doctrine\ORM\EntityManagerInterface $em */
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery(
            "SELECT count(intro)
            FROM IcsocSecurityBundle:WinRules intro
            WHERE 1=1 ".$where
        )->setParameters($parameter);
        try {
            $single = $query->getSingleResult();
            $count = $single['1'];
        } catch (NoResultException $e) {
            $count = 0;
        }
        if ($count > 0) {
            $totalPage = ceil($count/$rows);
        } else {
            $totalPage = 1;
        }
        if ($page > $totalPage) {
            $page = $totalPage;
        }
        $start = ($page -1 )*$rows;

        /** @var \Doctrine\ORM\Query $query */
        $query = $em->createQuery(
            "SELECT intro
            FROM IcsocSecurityBundle:WinRules intro
            WHERE 1=1 {$where}
            ORDER BY intro.".$sidx.' '.$sord
        )->setParameters($parameter);

        $query->setFirstResult($start);
        $query->setMaxResults($rows);
        $all = $query->getArrayResult();

        /**
         * @var  $key
         * @var \Icsoc\SecurityBundle\Entity\WinRules $v
         */
        foreach ($all as $k => $v) {
            $all[$k]['addTime'] = date("Y-m-d H:i:s", $v['addTime']);
            $week = explode("#", $v['weeks']);
            $sw = "";
            foreach ($week as $v1) {
                $sw .= isset($this->week[$v1])? $this->week[$v1]." " : '';
            }
            $all[$k]['weeks'] = $sw;
        }
        $reponse['rows'] = $all;
        $reponse['page'] = $page;
        $reponse['total'] = $totalPage;
        $reponse['records'] = $count;
        $serializer = $this->get('serializer');
        $response = $serializer->serialize($reponse, 'json');

        return new Response($response);
    }

    /**
     * 添加日程规则
     * @param Request $request
     * @return Response
     */
    public function addAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $vccId = $this->getVccId();
        if ($request->isMethod('post')) {
            $rule = new WinRules();
            $data = $request->request->all();
            $rule = $this->handRuleData($rule, $data);
            $rule->setAddTime(time());
            $rule->setVccId($vccId);
            $rule->setVccCode($this->getVccCode());
            $logStr = $this->get('translator')->trans('Add rule %str%', array('%str%'=>$rule->getRuleName()));
            $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_ADD, $logStr);
            $em->persist($rule);
            $em->flush();
            $data = array(
                'data'=>array(
                    'msg_detail'=> $this->trans('Add rule success'),
                    'type'=>'success',
                    'link' => array(
                        array(
                            'text'=>$this->trans('Continue to add rule'),
                            'href'=>$this->generateUrl('icsoc_rules_add'),
                        ),
                        array(
                            'text'=>$this->trans('Schedule list'),
                            'href'=>$this->generateUrl('icsoc_rules_list'),
                        ),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }
        $phones = $em->getRepository("IcsocSecurityBundle:CcPhone400s")
            ->getPhoneList("p.vccId = :vccId", array('vccId'=>$vccId));
        $ivrList = $em->getRepository("IcsocSecurityBundle:WinIvr")->getIvrList($vccId);

        return $this->render("IcsocRulesBundle:Rules:add.html.twig", array(
                'phones' => $phones,
                'ivrList' => $ivrList,
                'weeks' => $this->week,
                'nowDate' => date('Y-m-d'),
            ));
    }

    /**
     * 编辑日程规则；
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function editRuleAction(Request $request)
    {
        $id = $request->get("id", 0);
        $em = $this->getDoctrine()->getManager();
        $vccId = $this->getVccId();
        /** @var \Icsoc\SecurityBundle\Entity\WinRules $rule */
        $rule = $em->getRepository("IcsocSecurityBundle:WinRules")->findOneBy(array('ruleId'=>$id, 'vccId'=>$vccId));
        if (empty($rule)) {
            return $this->redirect($this->generateUrl('icsoc_rules_list'));
        }
        if ($request->isMethod('post')) {
            $data = $request->request->all();
            $this->handRuleData($rule, $data);
            $em->flush();
            //记录日志；
            $ruleInfo = $em->getRepository("IcsocSecurityBundle:WinRules")->getRuleInfo($id);
            $diff = array_diff_assoc($data, $ruleInfo);
            $content = "";
            foreach ($diff as $k => $v) {
                $content .= "[".$k."]:".$ruleInfo[$k]."=>".$data[$k]." ";
            }
            if ($content) {
                $logStr = $this->get('translator')->trans('Update rule %str%', array('%str%' => $content));
                $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_UPDATE, $logStr);
            }
            $data = array(
                'data'=>array(
                    'msg_detail'=> $this->trans('Update rule success'),
                    'type'=>'success',
                    'link' => array(
                        array(
                            'text'=>$this->trans('Add rule'),
                            'href'=>$this->generateUrl('icsoc_rules_add'),
                        ),
                        array(
                            'text'=>$this->trans('Schedule list'),
                            'href'=>$this->generateUrl('icsoc_rules_list'),
                        ),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }
        $weeks = $rule->getWeeks();
        $weeks = explode("#", $weeks);
        $rule->setWeeks($weeks);
        $phones = $em->getRepository("IcsocSecurityBundle:CcPhone400s")
            ->getPhoneList("p.vccId = :vccId", array('vccId'=>$vccId));
        $ivrList = $em->getRepository("IcsocSecurityBundle:WinIvr")->getIvrList($vccId);

        return $this->render("IcsocRulesBundle:Rules:edit.html.twig", array(
            'phones' => $phones,
            'ivrList' => $ivrList,
            'weeks' => $this->week,
            'nowDate' => date('Y-m-d'),
            'rule' => $rule,
            'rule_id' => $id,
        ));
    }

    /**
     * 删除日程规则
     * @param Request $request
     * @return JsonResponse
     */
    public function delRuleAction(Request $request)
    {
        $ids = $request->get('id', 0);
        $em = $this->getDoctrine()->getManager();
        $vccId = $this->getVccId();
        $where = "r.ruleId IN ($ids) AND r.vccId = '$vccId'";
        $res = $em->getRepository("IcsocSecurityBundle:WinRules")->delRules($where);
        if ($res > 0) {
            $logStr = $this->get('translator')->trans('Delete rule %str%', array('%str%' => $ids));
            $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_DELETE, $logStr);
            $error = false;
            $message = $this->trans('Delete success');
        } else {
            $error = true;
            $message = $this->trans('Delete fail');
        }

        return new JsonResponse(array('error'=>$error, 'message'=>$message));
    }

    /**
     * 检查日程规则是否存在
     * @param Request $request
     * @return Response
     */
    public function checkNameAction(Request $request)
    {
        $ruleName = $request->get("rule_name");
        $phoneId = $request->get("phone_id");
        $ruleId = (int) $request->get('rule_id');
        $vccId = $this->getVccId();
        $res = $this->getEm()->getRepository("IcsocSecurityBundle:WinRules")
            ->checkName($vccId, $ruleName, $phoneId, $ruleId);
        if ($res) {
            return new Response("false");
        }

        return new Response("true");
    }

    /**
     * 给rule对象设置值；
     * @param \Icsoc\SecurityBundle\Entity\WinRules $rule
     * @param $data
     * @return mixed
     */
    private function handRuleData($rule, &$data)
    {
        $em = $this->getDoctrine()->getManager();
        if (!empty($data['weeks'])) {
            $weeks = implode("#", $data['weeks']);
            $data['weeks'] = $weeks;
            $rule->setWeeks($weeks);
        } else {
            $rule->setWeeks('');
        }
        /** @var \Icsoc\SecurityBundle\Entity\WinIvr $ivr */
        $ivr = $em->getRepository("IcsocSecurityBundle:WinIvr")->find($data['ivr_id']);
        $rule->setIvrId($data['ivr_id']);
        if (!empty($ivr)) {
            $data['ivr_code'] = $ivr->getIvrCode();
            $data['ivr_name'] = $ivr->getIvrName();
            $rule->setIvrCode($data['ivr_code']);
            $rule->setIvrName($data['ivr_name']);
        }
        /** @var \Icsoc\SecurityBundle\Entity\CcPhone400s $phone */
        $phone = $em->getRepository("IcsocSecurityBundle:CcPhone400s")->find($data['phone_id']);
        $rule->setPhoneId($data['phone_id']);
        if (!empty($phone)) {
            $data['phone'] = $phone->getPhone();
            $data['phone400'] = $phone->getPhone400();
            $rule->setPhone($data['phone']);
            $rule->setPhone400($data['phone400']);
        } else {
            //全部号码都匹配
            $data['phone'] = '*';
            $data['phone400'] = '*';
            $rule->setPhone($data['phone']);
            $rule->setPhone($data['phone']);
            $rule->setPhone400($data['phone400']);
        }
        $data['start_date'] = empty($data['start_date']) || $data['sdate'] == 1 ? '*' : $data['start_date'];
        $data['end_date'] = empty($data['end_date']) || $data['edate'] == 1 ? '*' : $data['end_date'];
        $data['start_time'] = empty($data['start_time']) || $data['stime'] == 1 ? '*' : $data['start_time'];
        $data['end_time'] = empty($data['end_time']) || $data['etime'] == 1 ? '*' : $data['end_time'];

        $rule->setRuleName($data['rule_name']);
        $rule->setStartDate($data['start_date']);
        $rule->setEndDate($data['end_date']);
        $rule->setStartTime($data['start_time']);
        $rule->setEndTime($data['end_time']);
        $rule->setPriority($data['priority']);
        unset($data['sdate']);
        unset($data['edate']);
        unset($data['stime']);
        unset($data['etime']);
        
        return $rule;
    }
}
